import os, sys
from os.path import abspath, join, dirname
import time
from multiprocessing.managers import BaseManager
from multiprocessing import Process
import socket
import struct
import pyautogui
import cv2


class MyManager(BaseManager):
    pass


Port = 6018
Key = "Mouse Event"


def startManagerServer(port):
    MyManager.register("pyautogui", callable=lambda: pyautogui)
    # m = MyManager(address=("127.0.0.1", port), authkey=b"abracadabra")  # IP不填是默认为0.0.0.0
    m = MyManager(address=("0.0.0.0", port), authkey=b"abracadabra")  # IP不填是默认为0.0.0.0
    s = m.get_server()
    s.serve_forever()


def __initialize():
    # gpid = os.getpgid(os.getpid())
    # if "process_algorithm" not in dir():
    process_algorithm = Process(target=startManagerServer, args=(Port,))
    process_algorithm.daemon = True
    process_algorithm.start()


initialize = __initialize

if __name__ == "__main__":
    __initialize()

    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = "0.0.0.0"
    port = 6019

    size_of_int = 4
    num_ints = 4
    int_format = "I"  # 'I' 表示无符号整数

    server_socket.bind((host, port))
    server_socket.listen(1)

    print(f"鼠标服务已启动, Port:{port}")

    while True:
        client_socket, addr = server_socket.accept()
        print("连接地址: %s" % str(addr))
        press = False

        while True:
            try:
                data = client_socket.recv(size_of_int * num_ints)
                if len(data) == 0:
                    break

                event, x, y, flags = struct.unpack(int_format * num_ints, data)
                print(event, x, y, flags)

                if event == cv2.EVENT_LBUTTONDOWN:
                    pyautogui.mouseDown(x, y, button="left")

                elif event == cv2.EVENT_MOUSEMOVE:
                    if flags == cv2.EVENT_LBUTTONDOWN:
                        pyautogui.mouseDown(x, y, button="left")

                elif event == cv2.EVENT_LBUTTONUP:
                    pyautogui.mouseUp(x, y, button="left")

                # if event == cv2.EVENT_LBUTTONDOWN:
                #     press = True
                #     pyautogui.moveTo(x, y)
                #     pyautogui.mouseDown(button="left")

                # if event == cv2.EVENT_LBUTTONDOWN:
                #     if press:
                #         pyautogui.moveTo(x, y)
                #         pyautogui.mouseDown(button="left")

                # elif event == cv2.EVENT_LBUTTONUP:
                #     pyautogui.moveTo(x, y)
                #     pyautogui.mouseUp(button="left")

            except Exception as e:
                print(e)
                break

            # client_socket.send("消息已收到".encode())

        # 关闭连接
        client_socket.close()

    while True:
        time.sleep(100000)
